package com.xhu.base;

import java.util.List;

/**
 * 洋葱模型：增加或剥去随机加密层实现类
 * @author 王涛
 * @Created by WT on 2019/3/27.
 */
public class RNDOnion {
    /**
     * @param tableName  表名
     * @param columnNameList  列名List
     * @param password  主密钥
     * @return
     */
    public static String packOnRND(String tableName , List<String> columnNameList, String password){

        StringBuilder udfBuffer = new StringBuilder();
        udfBuffer.append("update "+tableName + " set ");
        String columnName = "";
        for(int index = 0; index < columnNameList.size(); index++){
            columnName = columnNameList.get(index);
            udfBuffer.append(columnName + " = to_base64(aes_encrypt("+columnName+",concat(rowid,"+"'"+password+"')))");
            if(index != (columnNameList.size() - 1)){
                udfBuffer.append(",");
            }
        }
        return udfBuffer.toString();
    }

    /**
     * @param tableName  表名
     * @param columnNameList  列名List
     * @param password  主密钥
     * @return
     */
    public static String peelOffRND(String tableName ,List<String> columnNameList,String password){
        StringBuilder udfBuffer = new StringBuilder();
        udfBuffer.append("update "+tableName + " set ");
        String columnName = "";
        for(int index = 0; index < columnNameList.size(); index++){
            columnName = columnNameList.get(index);
            udfBuffer.append(columnName + " = aes_decrypt(from_base64("+columnName+"),concat(rowid,"+"'"+password+"'"+"))");
            if(index != (columnNameList.size() - 1)){
                udfBuffer.append(",");
            }
        }
        return udfBuffer.toString();
    }


}
